package com.clwl.supervise.superviseapp.service.rectification;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.base.TsDept;
import com.clwl.supervise.superviseapp.entity.base.TsUser;
import com.clwl.supervise.superviseapp.entity.supervise.JgRectification;
import com.clwl.supervise.superviseapp.entity.supervise.JgRectificationContent;
import com.clwl.supervise.superviseapp.entity.supervise.JgRectificationImage;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsDeptMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsUserMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgRectificationContentMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgRectificationImageMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgRectificationMapper;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class RectificationService {


    @Resource
    private JgRectificationMapper rectificationMapper;


    @Resource
    private JgRectificationContentMapper rectificationContentMapper;


    @Resource
    private JgRectificationImageMapper rectificationImageMapper;


    @Resource
    private TcCompanyMapper companyMapper;


    @Resource
    private TsUserMapper userMapper;
    @Resource
    private TsDeptMapper tsDeptMapper;


    /**
     * 获取日常检查的企业列表
     *
     * @param pageNum  当前页数
     * @param pageSize 每页数据数量
     * @return
     */
    public IPage<Map<String, Object>> selectRectificationPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity) {
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        commonSearchEntity.setUserId(UserHelper.getUserId());
        commonSearchEntity.setDataRange(UserHelper.getUserInfo().getDataRange());
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());

        String dataRange = UserHelper.getUserInfo().getDataRange();
        commonSearchEntity.setUserId(UserHelper.getUserId());
        commonSearchEntity.setDataRange(dataRange);
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());
        commonSearchEntity.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            commonSearchEntity.setDataDeptId(dataDeptEntity.getId());
        } else {
            commonSearchEntity.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            commonSearchEntity.setIsSc("1");
        } else {
            commonSearchEntity.setIsSc("0");
        }

        List<String> processList = CompanyProcessUtil.getUserProcessList();
        commonSearchEntity.setProcessList(processList);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        Long dataCount = rectificationMapper.selectRectificationCount(commonSearchEntity);
        iPage.setTotal(dataCount);
        IPage<Map<String, Object>> pageList = rectificationMapper.selectRectificationPage(iPage, commonSearchEntity);
        for (Map<String, Object> record : pageList.getRecords()) {
            if (record == null) {
                continue;
            }
            if (record.get("PROBLEM_NUM").toString().equals("0")) {
                record.put("MANAGE_STATUS", "1");
            } else {
                record.put("MANAGE_STATUS", "0");
            }
            //获取业态信息
            Map<String, Object> companyInfo = companyMapper.selectBusinessFormatById(record.get("COMPANY_ID"));
            record.put("BUSINESS_TYPE", companyInfo != null ? companyInfo.get("BUSINESS_TYPE") : "");
            record.put("BUSINESS_TYPE_TWO", companyInfo != null ? companyInfo.get("BUSINESS_TYPE_TWO") : "");
        }
        return pageList;
    }

    /**
     * 获取整改单的问题项
     *
     * @param rectificationId 整改ID（在获取列表接口中有）
     * @return
     * @deprecated 问题整改功能中点击一个未整改的进入之后显示出问题项内容
     */
    public List<Map<String, Object>> selectRectificationItemList(Long rectificationId) {
        //根据id多  查询1  将1里的所有list  放到此list里
        List<JgRectificationImage> imageList = rectificationImageMapper.selectByRectificationId(rectificationId);
        List<Map<String, Object>> maps = rectificationContentMapper.selectByRectificationId(rectificationId);
        for (Map<String, Object> map : maps) {
            map.put("rectificationImageList", imageList);
        }
        return maps;
    }

    /**
     * 获取整改单的问题项
     *
     * @param rectificationItemId 整改问题项ID（在获取列表接口中有）
     * @param file                文件信息
     * @return
     * @deprecated 问题整改功能中点击一个未整改的进入之后显示出问题项内容
     */
    public String uploadRectificationItemFile(Long rectificationItemId, MultipartFile file) {
        try {
            JgRectificationContent rectificationContent = rectificationContentMapper.selectById(rectificationItemId);
            rectificationContent.setRectificationImage(FileUploadUtil.uploadFile(file, FileUploadEnum.rectification.getPath()).getFilePath());
            rectificationContentMapper.updateById(rectificationContent);
            return rectificationContent.getRectificationImage();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
    }

    /**
     * 保存整改情况信息
     *
     * @param rectificationId        整改ID（在获取列表接口中有）
     * @param supervisePersonalId1   核查人员ID1
     * @param supervisePersonalId2   核查人员ID2
     * @param verifyIdea             核查意见
     * @param verifyResult           核查结果 1-通过；2-不通过
     * @param temporary              是否临时1-是；2-否
     * @param transfertofile         是否转为立案1-是；2-否
     * @param rectificationTimeLimit 整改时限
     * @return
     * @deprecated 整改情况,
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRectificationInfo(Long rectificationId, Long supervisePersonalId1, Long supervisePersonalId2, String verifyIdea, String verifyResult, String temporary, String rectificationTimeLimit, String nextRectificationTimeLimit, String transfertofile) {
        JgRectification rectification = rectificationMapper.selectById(rectificationId);
        //不是临时保存的情况下才进行状态修改，和检查时间。
        if ("2".equals(temporary)) {
            if ("2".equals(temporary) && "2".equals(verifyResult)) {
                //整改不通过
                rectification.setCheckStatus("3");
            } else {
                //整改通过
                rectification.setCheckStatus("2");
            }
            rectification.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            rectification.setVerificationStatus("0");
        }
        rectification.setCheckResult(verifyResult);
        rectification.setCheckPersonnel1(supervisePersonalId1);
        rectification.setCheckPersonnel2(supervisePersonalId2);
        if (StringUtils.isBlank(transfertofile) || StringUtils.equals("undefined", transfertofile)) {
            rectification.setTransferToFile(null);
        } else {
            rectification.setTransferToFile(transfertofile);
        }
        rectification.setRectificationTimeLimit(rectificationTimeLimit);

        TsUser user = userMapper.selectById(supervisePersonalId1);
        if (user != null) {
            rectification.setCheckPersonnelName1(user.getName());
        }
        TsUser user2 = userMapper.selectById(supervisePersonalId2);
        if (user2 != null) {
            rectification.setCheckPersonnelName2(user2.getName());
        }
        rectification.setCheckOpinion(verifyIdea);
        rectification.setUpdateTime(new Date());
        rectification.setUpdateUserId(UserHelper.getUserId());
        rectification.setUpdateUserName(UserHelper.getUserInfo().getName());
        rectificationMapper.updateById(rectification);

        //如果整改不通过 则继续生成一个新的整改单,并且不是临时
        if ("2".equals(temporary) && "2".equals(verifyResult)) {
            JgRectification rectificationNew = new JgRectification();
            CopyOptions copyOptions = new CopyOptions();
            copyOptions.setIgnoreProperties("id", "checkStatus", "checkResult", "checkPersonnel1",
                    "checkPersonnel2", "checkPersonnelName1", "checkPersonnelName2", "checkOpinion");
            BeanUtil.copyProperties(rectification, rectificationNew, copyOptions);
            rectificationNew.setCheckStatus("1");
            rectificationNew.setRectificationTimeLimit(nextRectificationTimeLimit);
            rectificationNew.setCreateTime(new Date());
            rectificationNew.setCreatorId(UserHelper.getUserId());
            rectificationNew.setCreatorName(UserHelper.getUserInfo().getName());
            rectificationNew.setDeleteFlag(0L);
            rectificationNew.setParentId(rectification.getId());
            rectificationMapper.insert(rectificationNew);

            //生成整改项
            List<JgRectificationContent> contentList = rectificationContentMapper.selectEntityByRectificationId(rectification.getId());
            for (JgRectificationContent rectificationContent : contentList) {
                CopyOptions copyOptions1 = new CopyOptions();
                copyOptions1.setIgnoreProperties("id", "rectificationId", "rectificationImage");
                JgRectificationContent rectificationContentNew = new JgRectificationContent();
                BeanUtil.copyProperties(rectificationContent, rectificationContentNew, copyOptions1);
                rectificationContentNew.setCreateTime(new Date());
                rectificationContentNew.setCreatorId(UserHelper.getUserId());
                rectificationContentNew.setCreatorName(UserHelper.getUserInfo().getName());
                rectificationContentNew.setDeleteFlag(0L);
                rectificationContentNew.setRectificationId(rectificationNew.getId());
                rectificationContentMapper.insert(rectificationContentNew);
            }

        }

    }

    /**
     * 上传整改报告信息
     *
     * @param rectificationId 整改ID（在获取列表接口中有）
     * @param file            整改报告照片文件
     * @return
     * @deprecated 保存问题整改中的整改情况上传整改报告信息,
     */
    @Transactional(rollbackFor = Exception.class)
    public JgRectificationImage uploadRectificationFile(Long rectificationId, MultipartFile file) throws Exception {
        JgRectificationImage rectificationImage = new JgRectificationImage();
        rectificationImage.setRectificationId(rectificationId);
        FileResultEntity uploadFile = FileUploadUtil.uploadImage(file, FileUploadEnum.rectification.getPath());
        rectificationImage.setFileUrl(uploadFile.getFilePath());
        rectificationImage.setFileThUrl(uploadFile.getFileThPath());
        rectificationImage.setCreateTime(new Date());
        rectificationImage.setCreatorId(UserHelper.getUserId());
        rectificationImage.setCreatorName(UserHelper.getUserInfo().getName());
        rectificationImage.setDeleteFlag(0L);
        rectificationImageMapper.insert(rectificationImage);

        return rectificationImage;
    }

    /**
     * 获取问题整改的请改情况tab中的整改信息回显
     *
     * @param rectificationId 整改ID（在获取列表接口中有）
     * @return
     * @deprecated 获取问题整改的请改情况tab中的整改信息回显
     */
    public JgRectification getRectificationSituation(Long rectificationId) {
        JgRectification rectification = rectificationMapper.selectById(rectificationId);
        //获取通过此整改单检查不通过生成的子整改单
        QueryWrapper<JgRectification> rectificationQueryWrapper = new QueryWrapper<>();
        rectificationQueryWrapper.eq("delete_flag", "0");
        rectificationQueryWrapper.eq("parent_id", rectificationId);
        JgRectification rectificationChildren = rectificationMapper.selectOne(rectificationQueryWrapper);
        if (rectificationChildren != null) {
            rectification.setNextRectificationTimeLimit(rectificationChildren.getRectificationTimeLimit());
        }
        if (rectification.getCheckPersonnel1() == null) {
            rectification.setCheckPersonnel1(UserHelper.getUserId());
            rectification.setCheckPersonnelName1(UserHelper.getUserInfo().getName());
        }
        List<JgRectificationImage> imageList = rectificationImageMapper.selectByRectificationId(rectificationId);
        rectification.setRectificationImageList(imageList);

        TcCompany company = companyMapper.selectById(rectification.getCompanyId());
        rectification.setSubProcess(company.getSupProcess());
        if (rectification.getTransferToFile() == null) {
            rectification.setTransferToFile("2");
        }
        return rectification;
    }

    /**
     * @param rectificationId
     * @return
     */
    public JgRectification getRectificationInfo(Long rectificationId) {
        JgRectification rectification = rectificationMapper.selectById(rectificationId);
        List<JgRectificationContent> rectificationContentList = rectificationContentMapper.selectEntityByRectificationId(rectificationId);
        rectification.setRectificationContentList(rectificationContentList);
        return rectification;
    }

    public void deleteRectificationImage(Long id) {
        JgRectificationImage image = rectificationImageMapper.selectById(id);
        image.setDeleteFlag(1L);
        rectificationImageMapper.updateById(image);
    }
}
